from rest_framework import serializers

from books.models import BookInfo


def check_bpub_date(date):
    if date.year < 1980:
        raise serializers.ValidationError('')
    else:
        return date


def check_bpub_date1(date):
    if date.month > 11:
        raise serializers.ValidationError('')
    else:
        return date


class BookSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True, label="书籍编号")
    btitle = serializers.CharField(max_length=20, label="名称")
    bpub_date = serializers.DateField(label="发布日期", validators=[check_bpub_date, check_bpub_date1])
    bread = serializers.IntegerField(default=0, label="阅读量")
    bcomment = serializers.IntegerField(default=0, label="评论量")
    is_delete = serializers.BooleanField(default=False, label="逻辑删除")

    heroinfo_set = serializers.StringRelatedField(read_only=True, many=True)

    def create(self, validated_data):
        book = BookInfo.objects.create(**validated_data)
        return book

    def update(self, instance, validated_data):
        BookInfo.objects.filter(id=instance.id).update(**validated_data)

        return BookInfo.objects.get(id=instance.id)


    # def validate_btitle(self, attr):
    #     if not '西游' in attr:
    #         raise serializers.ValidationError('error value')
    #     else:
    #         return attr

    def validate_bread(self, read):
        if read > 50:
            raise serializers.ValidationError('bread should not be larger than 500')
        else:
            return read

    def validate(self, attrs):
        if attrs['bread'] < attrs['bcomment']:
            raise serializers.ValidationError('bcomment should not be larger than bread')

        else:
            return attrs


class HeroSerializer(serializers.Serializer):
    GENDER_CHOICES = (
        (0, 'male'),
        (1, 'female')
    )

    id = serializers.IntegerField(label='ID', read_only=True)
    hname = serializers.CharField(label='name', max_length=20)
    hgender = serializers.ChoiceField(choices=GENDER_CHOICES, label='gender', required=False, default=0)
    hcomment = serializers.CharField(label='details', max_length=200, required=False, allow_null=True)

    # hbook = serializers.PrimaryKeyRelatedField(queryset=BookInfo.objects.all())
    # hbook = serializers.PrimaryKeyRelatedField(read_only=True)
    # hbook = serializers.StringRelatedField(read_only=True)
    # hbook = serializers.StringRelatedField()
    hbook = BookSerializer(read_only=True)
    # hbook = BookSerializer()
